package com.mazihao.emos.controller;

import cn.hutool.json.JSONUtil;
import com.mazihao.emos.common.util.AjaxResult;
import com.mazihao.emos.config.shiro.JwtUtil;
import com.mazihao.emos.controller.form.LoginForm;
import com.mazihao.emos.controller.form.RegisterForm;
import com.mazihao.emos.controller.form.SearchMembersForm;
import com.mazihao.emos.controller.form.SearchUserGroupByDeptForm;
import com.mazihao.emos.exception.EmosException;
import com.mazihao.emos.service.UserService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.shiro.authz.annotation.Logical;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.validation.Valid;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Set;

/**
 * @author mazihao
 */
@RestController
@RequestMapping("/user")
@Api("用户模块web接口")
public class UserController {
    @Resource
    private UserService userService;

    @Resource
    private JwtUtil jwtUtil;

    @Resource
    private RedisTemplate<String, Object> redisTemplate;

    @Value("${emos.jwt.cache-expire}")
    private int cacheExpire;

    @PostMapping("/register")
    @ApiOperation("注册用户")
    public AjaxResult register(@Valid @RequestBody RegisterForm form){
        int id=userService.registerUser(form.getRegisterCode(),form.getCode(),form.getNickname(),form.getPhoto());
        String token=jwtUtil.createToken(id);
        Set<String> permsSet=userService.searchUserPermissions(id);
        saveCacheToken(token,id);
        return AjaxResult.ok("用户注册成功").put("token",token).put("permission",permsSet);
    }

    /**
     * 保存更新内存中的token
     */
    public void saveCacheToken(String token, int userId) {
        // token作为key，userId作为value，设置过期时间
        try {
            redisTemplate.opsForValue().set(token, userId+"", cacheExpire);
        } catch (Exception e) {
            throw new EmosException("Redis缓存失败");
        }
    }

    @PostMapping("/login")
    @ApiOperation("用户登录")
    public AjaxResult login(@Valid @RequestBody LoginForm form) {
        int id = userService.login(form.getCode());
        String token = jwtUtil.createToken(id);
        Set<String> permsSet = userService.searchUserPermissions(id);
        saveCacheToken(token, id);
        return AjaxResult.ok("登录成功").put("token", token).put("permission", permsSet);
    }


    @PostMapping("/addUser")
    @ApiOperation("添加用户")
    @RequiresPermissions(value = {"ROOT", "USER:ADD"}, logical = Logical.OR)
    public AjaxResult addUser() {
        return AjaxResult.ok("添加用户成功");
    }

    @GetMapping("/searchUserSummary")
    @ApiOperation("查询用户摘要信息")
    public AjaxResult searchUserSummary(@RequestHeader("token") String token) {
        int userId = jwtUtil.getUserId(token);
        HashMap<String, Object> map = userService.searchUserSummary(userId);
        return AjaxResult.ok().put("result", map);
    }

    @PostMapping("/searchUserGroupByDept")
    @ApiOperation("查询按部门分组的用户")
    @RequiresPermissions(value = {"ROOT", "EMPLOYEE:SELECT"}, logical = Logical.OR)
    public AjaxResult searchUserGroupByDept(@RequestBody @Valid SearchUserGroupByDeptForm form) {
        ArrayList<HashMap<String, Object>> list = userService.searchUserGroupByDept(form.getKeyword());
        return AjaxResult.ok().put("result", list);
    }

    @PostMapping("/searchMembers")
    @ApiOperation("查询成员")
    @RequiresPermissions(value = {"ROOT", "MEETING:INSERT", "MEETING:UPDATE"}, logical = Logical.OR)
    public AjaxResult searchMembers(@RequestBody @Valid SearchMembersForm form) {
        if (!JSONUtil.isJsonArray(form.getMembers())) {
            throw new EmosException("members不是JSON数组");
        }
        List<Integer> params = JSONUtil.parseArray(form.getMembers()).toList(Integer.class);
        return AjaxResult.ok().put("result", userService.searchMembers(params));
    }
}
